<?php

/**
 * @author Edison P. Quinones Jr
 * @version  1.0.0
 * @copyright 2008
 */

class RegisterController extends Zend_Controller_Action
{
	function init()
	{
		$this->initView();
		$this->view->baseUrl = $this->_request->getBaseUrl();
		$webInfoNamespace  = new Zend_Session_Namespace('webInfo');
		$this->view->webInfo = $webInfoNamespace->webInfo;
		Zend_Loader::loadClass('JumperAccount');
		Zend_Loader::loadClass('ConfirmationList');
		Zend_Loader::loadClass('Defaultprofile');
		Zend_Loader::loadClass('Zend_Filter_StripTags');
		Zend_Loader::loadClass('Zend_Validate_EmailAddress');
		Zend_Loader::loadClass('Zend_Validate_StringLength');

		$countWords = strlen($_SERVER['REQUEST_URI']);
		if (strpos($_SERVER['REQUEST_URI'], '/', $countWords-1) == true)
		{
			$this->_redirect(substr_replace($_SERVER['REQUEST_URI'], '', $countWords-1));
			//$this->view->testingLang = substr_replace($_SERVER['REQUEST_URI'], '', $countWords-1);
		}
		$this->view->user = Zend_Auth::getInstance()->getIdentity();
		
		# Links
		$registry = Zend_Registry::getInstance();
		$this->view->links = $registry->get('linksArray');
		# end of links
	}
	function indexAction()
	{
		$webInfoNamespace  = new Zend_Session_Namespace('webInfo');
		$webInfo = $webInfoNamespace->webInfo;
		
		$auth = Zend_Auth::getInstance();
		if ($auth->hasIdentity())
		{
			$this->_redirect($webInfo.'Jumpstart');
		}
		
		
		$filter = new Zend_Filter_StripTags();
		
		$lastVisit = $webInfoNamespace->lastVisit;
		
		if (!isset($lastVisit))
		{
			if(!isset($_SERVER['HTTP_REFERER']))
			{
				$webInfoNamespace->lastVisit = '';
			}
			else
			{
				$webInfoNamespace->lastVisit = $_SERVER['HTTP_REFERER'];
				//$webInfoNamespace->setExpirationSeconds(500);
			}
		}	
		
		//Headers
		$this->view->keywords = 'Edison, Quinones, Jr';
		$this->view->description = 'Groupjump jumper registration fill-up form';
		$this->view->author = 'Edison P. Quinones Jr.';
		$this->view->robots = 'Index';
		$this->view->title = 'Groupjump Registration.  Please fill up the form';
		$this->view->page = 'registration';
		

		

		$this->view->headerAdditional = '
		<!-- Include Ext and app-specific scripts: -->
		<script type="text/javascript" src="/jscripts/ExtStart2.js"></script>
	    
	    <!-- Include Ext stylesheets here: -->
	    <link rel="stylesheet" type="text/css" href="'.$webInfo.'nextix_2.0.1/resources/css/ext-all.css" />
		<link rel="stylesheet" type="text/css" href="'.$webInfo.'jscripts/passwordmeter.css" />

		<!-- Common Styles for the examples -->
		<link rel="stylesheet" type="text/css" href="'.$webInfo.'css/registration.css" />
		';

		$this->view->jumperEmail = trim($filter->filter($this->_request->getParam('email')));
		$this->view->secretQuestions = trim($filter->filter($this->_request->getParam('secretQuestions')));
		$this->view->secretAnswers = trim($filter->filter($this->_request->getParam('secretAnswers')));
		$this->view->jumperEmailError = trim($filter->filter($this->_request->getParam('jumperEmailError')));
		$this->view->charactersFromImageError = trim($filter->filter($this->_request->getParam('charactersFromImageError')));
		$this->view->passwordError = trim($filter->filter($this->_request->getParam('passwordError')));
		$this->view->firstAndLastNameError = trim($filter->filter($this->_request->getParam('firstAndLastNameError')));
		$this->view->jumperFirstName = trim ($filter->filter($this->_request->getParam('firstname')));
		$this->view->jumperLastName = trim($filter->filter($this->_request->getParam('lastname')));	
	}

	function checkemailAction()
	{
		$error_flag = 0;
		$filter = new Zend_Filter_StripTags();
		$validator = new Zend_Validate_EmailAddress();
		$jumperEmail = $filter->filter($this->_request->getPost('jumperEmail'));
		$jumperEmail = trim($jumperEmail);


		$jumper_account = new JumperAccount();
		$jumperView = $jumper_account->fetchAll();


		foreach($jumperView as $jumperView)
		{
			if ($validator->isValid($jumperEmail))
			{
				// email appears to be valid
				if (strcasecmp($jumperView->email_add,$jumperEmail)==0)
				{
					$error_flag = 1;
				}
			}
			else
			{
				// email is invalid; print the reasons
				foreach ($validator->getMessages() as $message)
				{
					$error_flag = 2;
					$this->view->awOk = "$message\n";
				}
			}
		}
		
		if ($error_flag == 1)
		{
			$this->view->awOk = "Email is existing";
		}
		elseif ($error_flag == 2)
		{
		
		}
		else 
		{
			$this->view->awOk = 'Email is available';
		}

	}
	function addAction()
	{
		$this->view->keywords = 'Edison, Quinones, Jr';
		$this->view->description = 'Groupjump jumper registration fill-up form';
		$this->view->author = 'Edison P. Quinones Jr.';
		$this->view->robots = 'Index';
		$this->view->title = 'Groupjump Registration.  Please fill up the form';

	
		
		$jumper_account = new JumperAccount();
		$confirmation_list = new ConfirmationList();
		$default_profile = new Defaultprofile();
		$webInfoNamespace  = new Zend_Session_Namespace('webInfo');
		$webInfo = $webInfoNamespace->webInfo;

		if ($this->_request->isPost())
		{
			$error_flag = false;
			
			$filter = new Zend_Filter_StripTags();
			$validator = new Zend_Validate_EmailAddress();
			$firstname = trim($filter->filter($this->_request->getPost('jumperFirstName')));
			$lastname = trim($filter->filter($this->_request->getPost('jumperLastName')));
			$jumperEmail = trim($filter->filter($this->_request->getPost('jumperEmail')));
			$password = trim($filter->filter($this->_request->getPost('password')));
			$confirmPassword = trim($filter->filter($this->_request->getPost('confirmPassword')));
			$characters = trim($filter->filter($this->_request->getPost('characters')));
			$secretQuestions = trim($filter->filter($this->_request->getPost('secretQuestions')));
			$secretAnswer = trim($filter->filter($this->_request->getPost('secretAnswer')));
			$lastVisited = $webInfoNamespace->lastVisit;


			$jumperView = $jumper_account->fetchAll();
			
			#check firstname and last name
			if ((!isset($firstname)) || (!isset($lastname)))
			{
				$error_flag = true;
				$firstAndLastNameError = 'Please dont leave the first and last name blank.';
			}
			elseif (($firstname == '') || ($lastname == ''))
			{
				$error_flag = true;
				$firstAndLastNameError = 'Please dont leave the first and last name blank.';
			}
			#end of checking firstname and last name


			#start of checking the email
			if ($jumperEmail != '')
			{
				foreach($jumperView as $jumperView)
				{
					if ($validator->isValid($jumperEmail))
					{
						// email appears to be valid
						if (strcasecmp($jumperView->email_add,$jumperEmail)==0)
						{
							//email is existing
							$error_flag = true;
							$jumperEmailError = 'Email is existing. <a href="/forgot">Please click forgot password link</a>';
						}
	
					}
					else
					{
						// email is invalid; print the reasons
						$error_flag = true;
						foreach ($validator->getMessages() as $message)
						{
							$jumperEmailError = $message."\n";
						}
					}
				}
			}
			else 
			{
				$error_flag = true;
				$jumperEmailError = 'Email is a required field';
			}
			#end of checking the email

			#check the password
			$passwordValidator = new Zend_Validate_StringLength(7);


			$passwordValidator->setMessage('The password is too short; it must be at least %min% characters',  Zend_Validate_StringLength::TOO_SHORT);


			if (strcasecmp($password,$confirmPassword)==0)
			{	
				if (!$passwordValidator->isValid($password))
				{
					$error_flag = true;
					$passwordError = current($passwordValidator->getMessages());
				}
			}
			else
			{
				$error_flag = true;
				$passwordError = 'The passwords did not match.';
			}
			#end of checking the password

			#check the image verification is correct
			$webInfoNamespace  = new Zend_Session_Namespace('characters');
			$charactersFromImage = $webInfoNamespace->characters;

			if ($charactersFromImage != null)
			{
				if(strcasecmp(sha1($characters),$charactersFromImage)!=0)
				{
					$error_flag=true;
					$charactersFromImageError = 'You have entered wrong verification code.  Please follow the right code shown on the image above.';
				}
			}
			else
			{
				$error_flag = true;
				$charactersFromImageError = 'Your image verification expired. Please input the image verification again. ';
			}
			#end of image verification


			#save the data to database and sending the confirmation email
			if($error_flag == false)
			{
				$verification_url = md5(sha1($jumperEmail));
				$confirmationUrl = $webInfo.'register/confirmation/user/'.md5(sha1($jumperEmail));
										
				$registry = Zend_Registry::getInstance();
				$senderEmail = $registry->get('emailUsername');
				$senderPassword = $registry->get('emailPassword');
				$senderName = $registry->get('emailName');
				$senderSmtp = $registry->get('emailSmtp');
				$senderSubject = $registry->get('emailSubject');
				$senderBodyText = 'Hi '.$firstname.' '.$lastname.',\n\n'.$registry->get('emailBodyText').'/n'.$confirmationUrl;
				$senderBodyHtml = 'Hi '.$firstname.' '.$lastname.',<br /><br />'.$registry->get('emailBodyHtml').'<br />'.$confirmationUrl;

				// Create transport
				Zend_Loader::loadClass('Zend_Mail');
				Zend_Loader::loadClass('Zend_Mail_Transport_Smtp');
				$config = array('auth' => 'login',
								'username' => $senderEmail,
								'password' => $senderPassword,
								'ssl' => 'tls');
				try 
				{
					$transport = new Zend_Mail_Transport_Smtp($senderSmtp, $config);
				}
				catch (Exception $e)
				{
					$this->view->mailError = $e;
				}

				Zend_Mail::setDefaultTransport($transport);
				$mail = new Zend_Mail();
				$mail->setFrom($senderEmail, $senderName);
				$mail->addTo($jumperEmail, $firstname.' '.$lastname);
				$mail->setSubject($senderSubject);
				$mail->setBodyText($senderBodyText);
				$mail->setBodyHtml($senderBodyHtml);
				
				try 
				{
					$mail->send($transport);
				}
				catch (Exception $e)
				{
					$this->view->mailError = $this->view->mailError.$e;
				}
				
				if (!isset($webInfoNamespace->lastVisit))
				{
					$lastVisited = '';
				}
				$this->view->lastVisited = $webInfoNamespace->lastVisit;
				$confirmationData = array ('last_visited' => $lastVisited, 'verification_url' => $verification_url);
				$confirmationId = $confirmation_list->insert($confirmationData); 
				
				$default_profileData = array('middle_name' => '',  'address' => '', 'gender' => '', 'gender' => '', 'birthdate' => '', 'about_me' => '');
				$defaultProfileId = $default_profile->insert($default_profileData);
				
				$data = array('email_add' => $jumperEmail, 'password' => sha1($password), 'secret_question'=> $secretQuestions, 'secret_answer' => sha1($secretAnswer), 'flag_confirm' => true, 'session_login' => '0', 'role_id'=> 1, 'profile_id' => $defaultProfileId, 'confirmation_id' => $confirmationId, 'first_name' => $firstname, 'last_name' => $lastname);
				
				$jumper_account->insert($data);
				
				//$this->_redirect('/');
			}
			elseif ($error_flag == true)
			{
				#end of saving the data to database and sending of confirmation
				$this->_redirect($webInfo.'register/index/email/'.$jumperEmail.'/jumperEmailError/'.$jumperEmailError.'/charactersFromImageError/'.$charactersFromImageError.'/passwordError/'.$passwordError.'/firstname/'.$firstname.'/lastname/'.$lastname.'/firstAndLastNameError/'.$firstAndLastNameError.'/secretQuestions/'.$secretQuestions.'/secretAnswers/'.$secretAnswer);
			}
			else 
			{
				$this->_redirect($webInfo.'/');
			}
			
		}
		else 
		{
			$this->_redirect($webInfo.'/');
		}
	}
	
	function confirmationAction()
	{
		$webInfoNamespace  = new Zend_Session_Namespace('webInfo');
		$webInfo = $webInfoNamespace->webInfo;
		$filter = new Zend_Filter_StripTags();
		$user = trim($filter->filter($this->_request->getParam('user')));
		$this->view->keywords = 'Edison, Quinones, Jr';
		$this->view->description = 'Groupjump jumper email confirmation pagef';
		$this->view->author = 'Edison P. Quinones Jr.';
		$this->view->robots = 'Index';
		$this->view->title = 'Groupjump Registration.  Email Confirmation';
		$confirmationList = new ConfirmationList();
		$jumper_account = new JumperAccount();
		$row = $confirmationList->fetchRow("verification_url = '".$user."'");
		
		if (isset($row->id))
		{
			$data = array('confirmation_id' => 0,'flag_confirm' => 0);
            $where = 'confirmation_id = ' . $row->id;
            $jumper_account->update($data, $where);
            $where = 'id = '.$row->id;
            $confirmationList->delete('id ='.$row->id);
			$this->view->userConfirmed = $row->id;
		}
		else 
		{
			$this->_redirect($webInfo.'/');
		}
	}
	function resendAction()
	{
		#resend the email
		
		#end of resending the email
		Zend_Auth::getInstance()->clearIdentity();
		//$this->_redirect('/');
	}
}